<template>
  <div id="app">
    <svg-icon></svg-icon>
    <transition :name="transitionName">
      <keep-alive :include="includePath">
        <router-view class="router"></router-view>
      </keep-alive>
    </transition>
    <ts-modal v-model="JPush_Order_Modal" title="平台派单" :closeTag="true" :lock="true" leftBtn="拒绝" rightBtn="接单"
              @onConfirm="takingOrder(pushOrder.id)" @onClose="ignoreOrder(pushOrder.id)">
      <ul class="jpush-order">
        <li class="list-item">
          <span class="label">服务类型：</span>
          <span class="value">{{pushOrder.class_name}}</span>
        </li>
        <li class="list-item">
          <span class="label">上门费用：</span>
          <span class="value">{{pushOrder.price}}</span>
        </li>
        <li class="list-item">
          <span class="label">上门时间：</span>
          <span class="value">{{pushOrder.make_time | fmtCommonDate}}</span>
        </li>
        <li class="list-item">
          <span class="label">服务位置：</span>
          <span class="value">{{pushOrder.address}}</span>
        </li>
        <li class="list-item" v-if="pushOrder.images&&pushOrder.images[0]!==''">
          <span class="label">故障照片：</span>
          <span class="value link" @click="showPhoto(pushOrder.images)">点击查看</span>
        </li>
        <li class="list-item" v-if="pushOrder.note">
          <span class="label">备注信息：</span>
          <span class="value">
            {{pushOrder.note}}
          </span>
        </li>
      </ul>
    </ts-modal>
    <div v-transfer-dom>
      <previewer :list="imgList" ref="previewer"></previewer>
    </div>
  </div>
</template>

<script>
  import svgIcon from './components/common/svgIcon.vue'
  import './assets/js/flexible'
  import transfer from './core/transfer'
  import TransferDom from './core/directives/transfer-dom'
  import {IGNORE_ORDER, ORDER_TAKING, GET_PUSH_ORDER, POST_UPLOCATION,EDIT_WORK_STATUS} from './assets/js/api'

  export default {
    name: 'app',
    components: {
      svgIcon,
      previewer(resolve) {
        require(['./components/tsui/previewer/previewer.vue'], resolve);
      }
    },
    data() {
      return {
        includePath: 'addProfile,authInfo,skillsLabel,range,info,profile',
        transitionName: 'slide-left',
        excludePath: {index: true, order: true, profile: true},
        //推送接单
        JPush_Order_Modal: false,
        imgList: [],
        pushOrder: {}
      }
    },
    directives: {
      TransferDom
    },
    async created() {
    },
    activated() {

    },
    async mounted() {
      //token失效后
      await transfer.$on('authFaild', () => {
         if($prod){
           window.JPush.deleteAlias({ sequence: 1 },
             (result) => {
               let sequence = result.sequence
             }, (error) => {
               let sequence = error.sequence
               let errorCode = error.code
             })
         }
//        this.includePath = this.includePath.replace(/,index,order/g, '');
      });
      //token失效登录后
//      await transfer.$on('loginBack', () => {
//        this.includePath += ',index,order,';
//      });
      this.initiateUI();
      this.receiveNotification();
      const {member_id, token} = this.$store.state.currentUser;
      this.baiduLocation();
    },
    methods: {
      initiateUI() {
        if ($prod) {
          try {
            //开启 JPush SDK 提供的推送服务
            window.JPush.init();
          } catch (exception) {
            alert('初始化推送错误，请联系客服');
          }
        }
      },
      receiveNotification() {
        let that = this;
        const store = that.$store;
        document.addEventListener("jpush.receiveNotification", async (event) => {
          //device.platform === "Android"
          const order_id = event.extras.order_id;
          const {token} = store.state.currentUser;
          if (order_id && token) {
            that.JPush_Order_Modal = true;
            const json = await that.$http.post(GET_PUSH_ORDER, {order_id}, {show: true});
            console.log(json)
            if (json.result === 1) {
              console.log(json)
              that.pushOrder = json.data;
            }
          }
        }, false)
      },
      //照片查看
      showPhoto(images) {
        this.imgList = [];
        images.map((item, key, arr) => {
          this.imgList.push({src: item});
        });
        this.$nextTick(() => {
          this.$refs.previewer.show(0)
        });
      },
      //发送定位
      baiduLocation() {
        setInterval(() => {
          if ($prod) {
            const {member_id, token} = this.$store.state.currentUser;
            if (token) {
              baidumap_location.getCurrentPosition(result => {
                const lat = result.latitude;
                const lng = result.longitude;
                this.$http.post(POST_UPLOCATION, {lat, lng});
              }, error => {
//                this.$toast('定位失败！请联系客服');
                console.log('定位失败！请联系客服')
              });
            }
          }
        }, 30000);
      },
      //拒绝订单
      async ignoreOrder(order_id) {
        const json = await this.$http.post(IGNORE_ORDER, {order_id}, {show: true});
        if (json.result === 1) {
          this.$toast('拒绝成功');
        }
      },
      //接单
      async takingOrder(order_id) {
        const json = await this.$http.post(ORDER_TAKING, {order_id, type: 2}, {show: true});
        if (json.result === 1) {
          this.JPush_Order_Modal = false;
          this.$toast('接单成功');
          this.$router.replace({name: 'order'})
        }
      }
    },
    watch: {
      '$route'(to, from) {
        let isBack = this.$router.isBack;
        const isInclude = this.excludePath[from.name];
        const isToInclude = this.excludePath[to.name];
        if (isBack) {
          this.transitionName = 'slide-right';
        } else {
          if (isInclude && isToInclude)
            this.transitionName = '';
          else
            this.transitionName = 'slide-left';
        }
        this.$router.isBack = false;
      }
    }
  }
</script>

<style lang="scss">
  @import "./assets/css/global";
  @import "./assets/css/mixin";
  @import "./assets/css/variables";
  @import "./assets/css/mint-settings";
  @import "./assets/css/jpush_order";

  .no-data {
    text-align: center;
    font-size: .28rem;
    margin-top: .20rem;
    color: #9a9a9a;
  }

  [v-cloak] {
    display: none;
  }

  .includeRouter {
    position: absolute;
    width: 100%;
    display: flex;
    flex-direction: column;
  }

  @mixin routeAnimation($duration) {
    z-index: $childZIndex;
    @extend .includeRouter;
    height: 100%;
    transition: all $duration ease-in-out;
    background-color: #F7F7F7;
  }

  .router {
    @include routeAnimation(.23s);
  }

  .slide-left-enter,
  .slide-right-leave-active {
    z-index: 1000;
    transform: translate3d(100%, 0, 0);
  }

  .slide-left-leave-active {
    transform: translate3d(-100px, 0, 0);
  }

  .slide-right-enter {
    transform: translate3d(-200px, 0, 0);
  }

  .slide-child-leave-active,
  .slide-child-enter {
    transform: translate3d(100%, 0, 0)
  }

  .child-route {
    @include fullScreen;
    transition: all .3s ease;
    z-index: $childZIndex;
  }
</style>
